package com.baizhi.wd.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.baizhi.wd.entity.User;
import com.baizhi.wd.util.JdbcUtil;

public class UserDaoImpl implements UserDao {

	// 1查一个
	public User selectOne(String username) {
		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;

		try {
			// 1-2
			con = JdbcUtil.getCon();

			// 3 pstm
			String sql = "select username,password from test_user where username=?";
			pstm = con.prepareStatement(sql);

			// 4 ?,execute
			pstm.setString(1, username);
			rs = pstm.executeQuery();

			// 5 处理查询结果
			if (rs.next()) {
				//  ֵ
				String name = rs.getString("username");
				String pwd = rs.getString("password");
				// 
				User user = new User(name, pwd);
				
				return user;
			}
			return null; //
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			// 6 释放资源
			JdbcUtil.release(rs, pstm, null);//dao�ķ����� ���ܹ�con
		}

	}
	//查所有
	public List<User> selectAll(){
		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try{
			//1-2
			con=JdbcUtil.getCon();
			//3
			String sql = "select username,password from test_user";
			pstm = con.prepareStatement(sql);
			//4
			rs = pstm.executeQuery();
			//5
			List<User> list = new ArrayList<>();
			while(rs.next()){
				String name = rs.getString("username");
				String pwd = rs.getString("password");
				User us = new User(name,pwd);
				list.add(us);
			}
			return list;
		}catch(Exception e){
			throw new RuntimeException(e);
		}finally {
			// 6 释放资源
			JdbcUtil.release(rs, pstm, null);//dao�ķ����� ���ܹ�con
		}
	}
	//添加一个
	public void insertUser(User user){
		Connection con = null;
		PreparedStatement pstm = null;
		try{
		//1 2
		con=JdbcUtil.getCon();
		//3 
		String sql = "insert into test_user values(?,?)";
		pstm = con.prepareStatement(sql);
		//4
		pstm.setString(1, user.getUsername());
		pstm.setString(2, user.getPassword());	

		int row=pstm.executeUpdate();
		System.out.println(row+"插入");
		//5
		}catch(Exception e){throw new RuntimeException(e);}
		finally{
		//6
			JdbcUtil.release(null, pstm, null);
		}
	}
}
